package cn.iocoder.yudao.module.crm.service.performance.person;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crm.controller.admin.performance.person.vo.PersonPerformanceConfigPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.performance.person.vo.PersonPerformanceConfigSaveReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.performance.person.PersonPerformanceConfigDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.performance.person.PersonPerformanceConfigDetailDO;
import cn.iocoder.yudao.module.crm.dal.mysql.performance.person.PersonPerformanceConfigDetailMapper;
import cn.iocoder.yudao.module.crm.dal.mysql.performance.person.PersonPerformanceConfigMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.PERFORMANCE_CONFIG_CONFLICT;
import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.PERFORMANCE_CONFIG_NOT_EXISTS;

/**
 * CRM_业绩配置 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class PersonPerformanceConfigServiceImpl implements PersonPerformanceConfigService {

    @Resource
    private PersonPerformanceConfigMapper personPerformanceConfigMapper;

    @Resource
    private PersonPerformanceConfigDetailMapper personPerformanceConfigDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createPerformanceConfig(PersonPerformanceConfigSaveReqVO createReqVO) {

        Long[] userIds = createReqVO.getUserIdS();
        for (Long userId : userIds) {
            // 先删除同年同员工同指标点的数据 保持一个员工一个年份一个指标点只有一条业绩指标配
            Map<String,Object> deleteMap = new HashMap<>();
            deleteMap.put("user_id",userId);
            deleteMap.put("year",createReqVO.getYear());
            deleteMap.put("performance_point", createReqVO.getPerformancePoint());
            personPerformanceConfigMapper.deleteByMap(deleteMap);
            QueryWrapper<PersonPerformanceConfigDetailDO> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("performance_point",createReqVO.getPerformancePoint());
            deleteWrapper.likeLeft("belong_month",createReqVO.getYear());
            deleteWrapper.eq("user_id",userId);
            personPerformanceConfigDetailMapper.delete(deleteWrapper);
            // 插入
            PersonPerformanceConfigDO performanceConfig = BeanUtils.toBean(createReqVO, PersonPerformanceConfigDO.class);
            performanceConfig.setUserId(userId);
            personPerformanceConfigMapper.insert(performanceConfig);
            List<PersonPerformanceConfigDetailDO> list = createDetailListFromReqVO(createReqVO,userId);
            personPerformanceConfigDetailMapper.insertBatch(list);
        }
    }
    private List<PersonPerformanceConfigDetailDO> createDetailListFromReqVO(PersonPerformanceConfigSaveReqVO createReqVO, Long userId) {
        List<PersonPerformanceConfigDetailDO> list = new ArrayList<>();

        PersonPerformanceConfigDetailDO monthDetail01 = new PersonPerformanceConfigDetailDO();
        monthDetail01.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail01.setBelongMonth(createReqVO.getYear()+"-01");
        monthDetail01.setUserId(userId);
        monthDetail01.setTargetValue(createReqVO.getTargetValue1());
        list.add(monthDetail01);

        PersonPerformanceConfigDetailDO monthDetail02 = new PersonPerformanceConfigDetailDO();
        monthDetail02.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail02.setBelongMonth(createReqVO.getYear()+"-02");
        monthDetail02.setUserId(userId);
        monthDetail02.setTargetValue(createReqVO.getTargetValue2());
        list.add(monthDetail02);

        PersonPerformanceConfigDetailDO monthDetail03 = new PersonPerformanceConfigDetailDO();
        monthDetail03.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail03.setBelongMonth(createReqVO.getYear()+"-03");
        monthDetail03.setUserId(userId);
        monthDetail03.setTargetValue(createReqVO.getTargetValue3());
        list.add(monthDetail03);

        PersonPerformanceConfigDetailDO monthDetail04 = new PersonPerformanceConfigDetailDO();
        monthDetail04.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail04.setBelongMonth(createReqVO.getYear()+"-04");
        monthDetail04.setUserId(userId);
        monthDetail04.setTargetValue(createReqVO.getTargetValue4());
        list.add(monthDetail04);

        PersonPerformanceConfigDetailDO monthDetail05 = new PersonPerformanceConfigDetailDO();
        monthDetail05.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail05.setBelongMonth(createReqVO.getYear()+"-05");
        monthDetail05.setUserId(userId);
        monthDetail05.setTargetValue(createReqVO.getTargetValue5());
        list.add(monthDetail05);

        PersonPerformanceConfigDetailDO monthDetail06 = new PersonPerformanceConfigDetailDO();
        monthDetail06.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail06.setBelongMonth(createReqVO.getYear()+"-06");
        monthDetail06.setUserId(userId);
        monthDetail06.setTargetValue(createReqVO.getTargetValue6());
        list.add(monthDetail06);

        PersonPerformanceConfigDetailDO monthDetail07 = new PersonPerformanceConfigDetailDO();
        monthDetail07.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail07.setBelongMonth(createReqVO.getYear()+"-07");
        monthDetail07.setUserId(userId);
        monthDetail07.setTargetValue(createReqVO.getTargetValue7());
        list.add(monthDetail07);

        PersonPerformanceConfigDetailDO monthDetail08 = new PersonPerformanceConfigDetailDO();
        monthDetail08.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail08.setBelongMonth(createReqVO.getYear()+"-08");
        monthDetail08.setUserId(userId);
        monthDetail08.setTargetValue(createReqVO.getTargetValue8());
        list.add(monthDetail08);

        PersonPerformanceConfigDetailDO monthDetail09 = new PersonPerformanceConfigDetailDO();
        monthDetail09.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail09.setBelongMonth(createReqVO.getYear()+"-09");
        monthDetail09.setUserId(userId);
        monthDetail09.setTargetValue(createReqVO.getTargetValue9());
        list.add(monthDetail09);

        PersonPerformanceConfigDetailDO monthDetail10 = new PersonPerformanceConfigDetailDO();
        monthDetail10.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail10.setBelongMonth(createReqVO.getYear()+"-10");
        monthDetail10.setUserId(userId);
        monthDetail10.setTargetValue(createReqVO.getTargetValue10());
        list.add(monthDetail10);

        PersonPerformanceConfigDetailDO monthDetail11 = new PersonPerformanceConfigDetailDO();
        monthDetail11.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail11.setBelongMonth(createReqVO.getYear()+"-11");
        monthDetail11.setUserId(userId);
        monthDetail11.setTargetValue(createReqVO.getTargetValue11());
        list.add(monthDetail11);

        PersonPerformanceConfigDetailDO monthDetail12 = new PersonPerformanceConfigDetailDO();
        monthDetail12.setPerformancePoint(createReqVO.getPerformancePoint());
        monthDetail12.setBelongMonth(createReqVO.getYear()+"-12");
        monthDetail12.setUserId(userId);
        monthDetail12.setTargetValue(createReqVO.getTargetValue12());
        list.add(monthDetail12);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePerformanceConfig(PersonPerformanceConfigSaveReqVO updateReqVO) {
        // 校验存在
        PersonPerformanceConfigDO oldData = personPerformanceConfigMapper.selectById(updateReqVO.getId());
        if (oldData == null) {
            throw exception(PERFORMANCE_CONFIG_NOT_EXISTS);
        }else{
            // 校验冲突
            validatePerformanceConfigConflict(updateReqVO);
            // 更新
            PersonPerformanceConfigDO updateObj = BeanUtils.toBean(updateReqVO, PersonPerformanceConfigDO.class);
            personPerformanceConfigMapper.updateById(updateObj);

            //删除明细表的旧数据 插入新数据
            QueryWrapper<PersonPerformanceConfigDetailDO> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("user_id", oldData.getUserId());
            deleteWrapper.likeLeft("belong_month",oldData.getYear());
            deleteWrapper.eq("performance_point", oldData.getPerformancePoint());
            personPerformanceConfigDetailMapper.delete(deleteWrapper);// 删除同年份 同部门 同指标点的数据
            List<PersonPerformanceConfigDetailDO> list = createDetailListFromReqVO(updateReqVO, updateReqVO.getUserId());
            personPerformanceConfigDetailMapper.insertBatch(list);
        }

    }

    private void validatePerformanceConfigConflict(PersonPerformanceConfigSaveReqVO updateReqVO) {
        QueryWrapper<PersonPerformanceConfigDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("performance_point",updateReqVO.getPerformancePoint());
        queryWrapper.eq("year",updateReqVO.getYear());
        queryWrapper.eq("user_id",updateReqVO.getUserId());
        queryWrapper.ne("id",updateReqVO.getId());
        List<PersonPerformanceConfigDO> list = personPerformanceConfigMapper.selectList(queryWrapper);
        if(!list.isEmpty()){
            throw exception(PERFORMANCE_CONFIG_CONFLICT);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)

    public void deletePerformanceConfig(Long id) {
        // 校验存在
        validatePerformanceConfigExists(id);
        PersonPerformanceConfigDO oldData = personPerformanceConfigMapper.selectById(id);
        QueryWrapper<PersonPerformanceConfigDetailDO> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("user_id", oldData.getUserId());
        deleteWrapper.likeLeft("belong_month",oldData.getYear());
        deleteWrapper.eq("performance_point", oldData.getPerformancePoint());
        personPerformanceConfigDetailMapper.delete(deleteWrapper);// 删除同年份 同员工 同指标点的数据
        // 删除
        personPerformanceConfigMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePerformanceConfigListByIds(List<Long> ids) {
        List<PersonPerformanceConfigDO> oldDataList = personPerformanceConfigMapper.selectByIds(ids);
        for(PersonPerformanceConfigDO oldData : oldDataList){
            //删除明细表的旧数据
            QueryWrapper<PersonPerformanceConfigDetailDO> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("user_id", oldData.getUserId());
            deleteWrapper.likeLeft("belong_month",oldData.getYear());
            deleteWrapper.eq("performance_point", oldData.getPerformancePoint());
            personPerformanceConfigDetailMapper.delete(deleteWrapper);// 删除同年份 同员工 同指标点的数据
        }
        // 删除
        personPerformanceConfigMapper.deleteByIds(ids);


    }


    private void validatePerformanceConfigExists(Long id) {
        if (personPerformanceConfigMapper.selectById(id) == null) {
            throw exception(PERFORMANCE_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public PersonPerformanceConfigDO getPerformanceConfig(Long id) {
        return personPerformanceConfigMapper.selectById(id);
    }

    @Override
    public PageResult<PersonPerformanceConfigDO> getPerformanceConfigPage(PersonPerformanceConfigPageReqVO pageReqVO) {
        return personPerformanceConfigMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PersonPerformanceConfigDO> getPerformanceConfigResultList(PersonPerformanceConfigPageReqVO pageReqVO) {
        personPerformanceConfigMapper.selectList(pageReqVO);
        return Collections.emptyList();
    }

}